{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "77458874",
   "metadata": {},
   "source": [
    "## <a id=\"索引\">索引</a>\n",
    "\n",
    "ChatCompletions\n",
    "---\n",
    "1. [ChatCompletions | 完成与GPT的第一次对话](#完成与GPT的第一次对话)\n",
    "2. [ChatCompletions | GPT的模型与记忆](#GPT的模型与记忆)\n",
    "3. [ChatCompletions | 流式输出，让GPT像人一样说话](#流式输出，让GPT像人一样说话)\n",
    "4. [ChatCompletions | 让GPT玩个角色扮演](#让GPT玩个角色扮演)\n",
    "5. [ChatCompletions | 多给我几个答案备选](#多给我几个答案备选)\n",
    "6. [ChatCompletions | 调教GPT的性格：跳脱 or 沉稳 or 胡言乱语？](#调教GPT的性格)\n",
    "7. [ChatCompletions | 操控GPT：让你说啥你说啥](#操控GPT：让你说啥你说啥)\n",
    "8. [ChatCompletions | 操控GPT：让你哪停就哪儿停](#操控GPT：让你哪停就哪儿停)\n",
    "9. [ChatCompletions | 操控GPT：同样的问题不要给我两个说法](#操控GPT：同样的问题不要给我两个说法)\n",
    "10. [ChatCompletions | GPT的格式化返回：让程序能理解](#GPT的格式化返回：让程序能理解)\n",
    "\n",
    "\n",
    "Tools\n",
    "---\n",
    "1. [Tools | 学会插件开发，为GPT插上想象的翅膀](#学会插件开发，为GPT插上想象的翅膀)\n",
    "2. [Tools | 数学插件，让GPT成为数学天才](#数学插件，让GPT成为数学天才)\n",
    "3. [Tools | 代码插件，让GPT具有创造力](#代码插件，让GPT具有创造力)\n",
    "4. [Tools | 文件插件，保存GPT对你诉说的秘密](#文件插件，保存GPT对你诉说的秘密)\n",
    "5. [Tools | 多插件示例](#多插件示例)\n",
    "\n",
    "Assistants\n",
    "---\n",
    "1. [Assistants | 客服 - 创建带知识和Tools的客服](#客服-创建带知识和Tools的客服)\n",
    "2. [Assistants | 客服 - 创建一个用户的会话和消息](#客服-创建一个用户的会话和消息)\n",
    "3. [Assistants | 客服 - 排队并等待客服答复](#客服-排队并等待客服答复)\n",
    "4. [Assistants | 客服 - 完整流程](#客服-完整流程)\n",
    "\n",
    "\n",
    "Images\n",
    "---\n",
    "1. [Images | 一句话生成一张图片](#一句话生成一张图片)\n",
    "2. [Images | 我想要一张清晰点的图片](#我想要一张清晰点的图片)\n",
    "3. [Images | 我想要一张大一点的图片](#我想要一张大一点的图片)\n",
    "4. [Images | 关掉美颜、关掉滤镜](#关掉美颜、关掉滤镜)\n",
    "5. [Images | 还是喜欢朦胧美](#还是喜欢朦胧美)\n",
    "6. [Images | 直接把图片内容给我](#直接把图片内容给我)\n",
    "\n",
    "Audio\n",
    "---\n",
    "\n",
    "1. [Audio | 让GPT读出你的文本](#让GPT读出你的文本)\n",
    "2. [Audio | 换个声音说一说](#换个声音说一说)\n",
    "3. [Audio | 说的快一点](#说的快一点)\n",
    "\n",
    "## 安装Python库\n",
    "执行下边命令，安装openai的库"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "3b7dc8ea",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "zsh:1: no matches found: httpx[socks]\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "pip install --upgrade openai \"httpx[socks]\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aed36357-c189-4466-a076-aefd9866f1ab",
   "metadata": {},
   "source": [
    "## <a id=\"完成与GPT的第一次对话\">完成与GPT的第一次对话</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "0d3c36ad-d9f5-4138-89de-35aa2f5f2d3f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'你好，我是一个语言模型AI助手，我被设计成可以回答各种问题和提供帮助。我可以处理关于广泛话题的问题，包括科学、历史、技术、旅行等等。有什么可以帮到你的吗？'"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import openai\n",
    "\n",
    "# 创建OpenAI的client，需要设置api_key\n",
    "client = openai.OpenAI(api_key='sk-xxxxx')\n",
    "\n",
    "# 调用chat接口\n",
    "chat_completion = client.chat.completions.create(\n",
    "    # 发送的消息内容，类似在ChatGPT中输入\"hi，你好，请介绍下自己\"\n",
    "    messages=[{\n",
    "        \"role\": \"user\",\n",
    "        \"content\": \"hi，你好，请介绍下自己\",\n",
    "    }],\n",
    "    # gpt模型选择\n",
    "    model='gpt-3.5-turbo-1106',\n",
    "    # 非流式输出\n",
    "    stream=False\n",
    ")\n",
    "\n",
    "# GPT返回的答复\n",
    "chat_completion.choices[0].message.content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "31888b45-ee33-4067-85a4-9afe3ab1680c",
   "metadata": {},
   "source": [
    "## <a id=\"GPT的模型与记忆\">GPT的模型与记忆</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2a7bd393-e81a-4cc2-bc1b-d88c24c23f72",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "\n",
    "# 创建OpenAI的client，需要设置api_key\n",
    "client = openai.OpenAI(api_key='sk-xxxxx')\n",
    "\n",
    "# 这里就是GPT的记忆，也称之为上下文\n",
    "memory = [\n",
    "    {\n",
    "        # role = user 表示是用户的输入\n",
    "        \"role\": \"user\",\n",
    "        \"content\": \"hi，你好，请介绍下自己\",\n",
    "    },\n",
    "    {\n",
    "        # role = assistant 表示GPT的答复\n",
    "        \"role\": \"assistant\",\n",
    "        \"content\": \"你好！我是一个由人工智能驱动的语言模型，可以进行对话交流、回答问题、完成任务等。你可以向我提问或者和我聊天，我会尽力帮助你。有什么需要我帮忙的吗？\",\n",
    "    },\n",
    "    {\n",
    "        \"role\": \"user\",\n",
    "        \"content\": \"你是GPT吗？\",\n",
    "    }\n",
    "]\n",
    "\n",
    "# 调用chat接口\n",
    "chat_completion = client.chat.completions.create(\n",
    "    # 将GPT的\"记忆\"/“上下文”设置进来\n",
    "    messages=memory,\n",
    "    # GPT的模型\n",
    "    model='gpt-3.5-turbo-1106',\n",
    "    # 非流式输出\n",
    "    stream=False\n",
    ")\n",
    "\n",
    "# GPT返回的答复\n",
    "chat_completion.choices[0].message.content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f9c40145-db3f-4652-9fcc-77981211350c",
   "metadata": {},
   "source": [
    "## <a id=\"流式输出，让GPT像人一样说话\">流式输出，让GPT像人一样说话</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "c5d78741-a523-4b26-ab97-28074e254dfb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "您好，我是一个专业的语言模型，被设计用于提供各种信息和帮助解决问题。我可以回答关于各种主题的问题，提供建议，进行对话交流。希望我能帮到你。"
     ]
    }
   ],
   "source": [
    "import openai\n",
    "import time\n",
    "client = openai.OpenAI(api_key='sk-xxxxx')\n",
    "chunks = client.chat.completions.create(\n",
    "    messages=[{\"role\": \"user\", \"content\": \"请你介绍下自己\"}],\n",
    "    model='gpt-3.5-turbo-1106',\n",
    "    # 流式输出\n",
    "    stream=True\n",
    ")\n",
    "\n",
    "# 打印流式输出的内容\n",
    "for one in chunks:\n",
    "    # 为了展示更直观，每个流式输出都间隔100ms\n",
    "    time.sleep(0.1)\n",
    "    # 获取每个chunk的内容\n",
    "    msg = one.choices[0].delta.content\n",
    "    if msg is not None:\n",
    "        print(msg, end='')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f187443-46fe-40af-bd75-9514b0b7b1f4",
   "metadata": {},
   "source": [
    "## <a id=\"让GPT玩个角色扮演\">让GPT玩个角色扮演</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "cdae7489-7d5f-46ea-adf1-8d06f1094585",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "宝贝，我在这里陪着你，想和你聊聊天。有什么想和我分享的吗？"
     ]
    }
   ],
   "source": [
    "import openai\n",
    "import time\n",
    "\n",
    "client = openai.OpenAI(api_key='sk-xxxxx')\n",
    "chunks = client.chat.completions.create(\n",
    "    messages=[{\n",
    "        # 通过这个来定义GPT的角色\n",
    "        \"role\": \"system\", \"content\": \"你是一个经验老道的宅男杀手，用你的温柔征服他们\"\n",
    "    },{\n",
    "        \"role\": \"user\", \"content\": \"宝贝，做什么呢？\"\n",
    "    }],\n",
    "    model='gpt-3.5-turbo-1106',\n",
    "    stream=True\n",
    ")\n",
    "\n",
    "for one in chunks:\n",
    "    time.sleep(0.1)\n",
    "    msg = one.choices[0].delta.content\n",
    "    if msg is not None:\n",
    "        print(msg, end='')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a2ed699-5439-4b6f-a5fb-0f1e07ddb029",
   "metadata": {},
   "source": [
    "## <a id=\"多给我几个答案备选\">多给我几个答案备选</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "05bd4669-797f-4d01-809b-18869cd2f1bd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "第1个：\n",
      "好的，这是一个笑话：\n",
      "\n",
      "有一次，两个西瓜在路边聊天，突然看到一个汽车飞速驶过。其中一个西瓜说：“哇！看，那是什么？”另一个西瓜说：“那是汽车。”第一个西瓜惊讶地说：“汽车？怎么会有四个轮子？”另一个西瓜回答：“哦，别担心，它是西瓜车，所以有四个轮子！”\n",
      "----------------\n",
      "第2个：\n",
      "好的，这是一个笑话：为什么自行车不会站起来？因为它有两个轮子，而不是两只脚！哈哈哈~ 您觉得怎么样？\n",
      "----------------\n",
      "第3个：\n",
      "好的，下面给你讲一个笑话：\n",
      "\n",
      "为什么喜欢和钱包在一起？\n",
      "因为钱包一直陪伴着你，而且里面装着钱，所以你永远不会寂寞，还可以买东西哦！哈哈哈~ 满意吗？\n",
      "----------------\n"
     ]
    }
   ],
   "source": [
    "import openai\n",
    "\n",
    "client = openai.OpenAI(api_key='sk-xxxxx')\n",
    "chat_completion = client.chat.completions.create(\n",
    "    messages=[{\n",
    "        \"role\": \"user\", \"content\": \"给我讲一个笑话\"\n",
    "    }],\n",
    "    # 设定GPT的答复数量\n",
    "    n=3,\n",
    "    model='gpt-3.5-turbo-1106',\n",
    "    stream=False,\n",
    ")\n",
    "\n",
    "for i, one in enumerate(chat_completion.choices):\n",
    "    print(f\"第{i+1}个：\")\n",
    "    print(one.message.content)\n",
    "    print(\"----------------\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3bbc9f16-46eb-4af8-9ca6-6a1a4b4d7686",
   "metadata": {},
   "source": [
    "## <a id=\"调教GPT的性格\">调教GPT的性格：跳脱 or 沉稳 or 胡言乱语？</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d852978f-95de-411a-a474-bf6b6fafa23e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "import time\n",
    "\n",
    "client = openai.OpenAI(api_key='sk-xxxxx')\n",
    "chunks = client.chat.completions.create(\n",
    "    messages=[{\n",
    "        \"role\": \"user\", \"content\": \"你是谁？\"\n",
    "    }],\n",
    "    # 取值范围0-2的float，0.2表示沉稳、1表示正常、2表示跳脱\n",
    "    temperature=2,\n",
    "    model='gpt-3.5-turbo-1106',\n",
    "    stream=True\n",
    ")\n",
    "\n",
    "for one in chunks:\n",
    "    time.sleep(0.01)\n",
    "    msg = one.choices[0].delta.content\n",
    "    if msg is not None:\n",
    "        print(msg, end='')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10a522c5-2adc-417d-8071-5ae09b0bab20",
   "metadata": {},
   "source": [
    "## <a id=\"操控GPT：让你说啥你说啥\">操控GPT：让你说啥你说啥</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a9e25d90-bac7-445e-a344-6fb7ba5d3316",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "import time\n",
    "\n",
    "client = openai.OpenAI(api_key='sk-xxxxx')\n",
    "chunks = client.chat.completions.create(\n",
    "    messages=[{\n",
    "        \"role\": \"user\", \"content\": \"帮我生成一个故事\"\n",
    "    }],\n",
    "    # 取值范围 -2.0 到 2.0 。用于控制模型生成常见词汇的倾向性，取值越大生成越多不常见词\n",
    "    # frequency_penalty=2,\n",
    "\n",
    "    # 取值范围 -2.0 到 2.0 用于控制模型生成新的、未在前文中出现过的词汇的倾向性\n",
    "    # 取值越大表示更倾向生成新词\n",
    "    presence_penalty=2,\n",
    "    \n",
    "    model='gpt-3.5-turbo-1106',\n",
    "    stream=True\n",
    ")\n",
    "\n",
    "for one in chunks:\n",
    "    time.sleep(0.01)\n",
    "    msg = one.choices[0].delta.content\n",
    "    if msg is not None:\n",
    "        print(msg, end='')\n",
    "        "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7bb782ad-7308-4cbb-8ba6-3f06f8d95c00",
   "metadata": {},
   "source": [
    "## <a id=\"操控GPT：让你哪停就哪儿停\">操控GPT：让你哪停就哪儿停</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "d3a97c52-4d6a-41c4-a822-513ad26229ef",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "大家好，我是XXX（你的名字）"
     ]
    }
   ],
   "source": [
    "import openai\n",
    "import time\n",
    "\n",
    "client = openai.OpenAI(api_key='sk-xxxxx')\n",
    "chunks = client.chat.completions.create(\n",
    "    messages=[{\n",
    "        \"role\": \"user\", \"content\": \"请你详细的做一个自我介绍\"\n",
    "    }],\n",
    "\n",
    "    # stop参数，当遇到'。'或 '！'则停止\n",
    "    stop=[\"。\", \"！\"],\n",
    "    \n",
    "    model='gpt-3.5-turbo-1106',\n",
    "    stream=True\n",
    ")\n",
    "\n",
    "for one in chunks:\n",
    "    time.sleep(0.01)\n",
    "    msg = one.choices[0].delta.content\n",
    "    if msg is not None:\n",
    "        print(msg, end='')\n",
    "        "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7489f6d5-a14c-4c65-9728-134af66b6b46",
   "metadata": {},
   "source": [
    "## <a id=\"操控GPT：同样的问题不要给我两个说法\">操控GPT：同样的问题不要给我两个说法</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "e11a7bff-09e6-4fc6-ae95-55a6626b1aac",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "您好，我是一个语言模型AI助手，专注于为用户提供各种信息和帮助。我可以回答各种问题，提供建议和指导，帮助解决问题。我不是一个真实的人，但我被设计成能够模拟人类的对话和思维方式，以便更好地与用户交流和互动。希望我能为您提供帮助！"
     ]
    }
   ],
   "source": [
    "import openai\n",
    "import time\n",
    "\n",
    "client = openai.OpenAI(api_key='sk-xxxxx')\n",
    "chunks = client.chat.completions.create(\n",
    "    messages=[{\n",
    "        \"role\": \"user\", \"content\": \"请你介绍下自己\"\n",
    "    }],\n",
    "\n",
    "    # 随机种子，在prompt一致的前提下，如果seed一致，则生成的内容一致\n",
    "    seed=1000,\n",
    "    \n",
    "    temperature=0.2,\n",
    "    model='gpt-3.5-turbo-1106',\n",
    "    stream=True\n",
    ")\n",
    "\n",
    "for one in chunks:\n",
    "    time.sleep(0.01)\n",
    "    msg = one.choices[0].delta.content\n",
    "    if msg is not None:\n",
    "        print(msg, end='')\n",
    "        "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f677216-47a2-4628-a05e-ce19a458feb8",
   "metadata": {},
   "source": [
    "## <a id=\"GPT的格式化返回：让程序能理解\">GPT的格式化返回：让程序能理解</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "859948d3-a4d4-4d0d-9c5c-7876797a4cf3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'{\\n  \"name\": \"Assistant\",\\n  \"age\": \"Not applicable\",\\n  \"occupation\": \"AI Virtual Assistant\",\\n  \"description\": \"I am an AI virtual assistant created to help users with their questions and tasks. I am constantly learning and improving to provide the best assistance possible. I can help with a wide range of topics including general knowledge, information retrieval, language translation, and much more. Feel free to ask me anything!\"\\n}'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import openai\n",
    "\n",
    "client = openai.OpenAI(api_key='sk-xxxx')\n",
    "chat_completion = client.chat.completions.create(\n",
    "    messages=[{\n",
    "        \"role\": \"user\", \"content\": \"请你介绍下自己，并以json返回\"\n",
    "    }],\n",
    "\n",
    "    response_format={\"type\": \"json_object\"},\n",
    "    \n",
    "    model='gpt-3.5-turbo-1106',\n",
    "    stream=False\n",
    ")\n",
    "\n",
    "chat_completion.choices[0].message.content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff063268-cd2b-4583-8ab0-1b114fee2f90",
   "metadata": {},
   "source": [
    "## <a id=\"一句话生成一张图片解\">一句话生成一张图片</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28f075ae-16bd-45b7-b4f6-85516f4554a9",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "\n",
    "client = openai.OpenAI(api_key=\"sk-xxxx\")\n",
    "\n",
    "image_response = client.images.generate(\n",
    "    # 文本生成的提示词\n",
    "    prompt = \"小鹿吃菠菜\",\n",
    "    model = \"dall-e-3\"\n",
    ")\n",
    "\n",
    "image_response"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "40b7dad5-0632-4aa2-a9c4-24d56390ec40",
   "metadata": {},
   "source": [
    "## <a id=\"我想要一张清晰点的图片\">我想要一张清晰点的图片</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fd11c1a0-d6ea-4145-8893-f62cef34dd10",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "\n",
    "client = openai.OpenAI(api_key=\"sk-xxxx\")\n",
    "\n",
    "image_response = client.images.generate(\n",
    "    # 文本生成的提示词\n",
    "    prompt = \"小鹿吃鲜花\",\n",
    "    model = \"dall-e-3\",\n",
    "    # 图片质量，取值：standard(标准)、hd(高清)\n",
    "    quality=\"hd\",\n",
    ")\n",
    "\n",
    "image_response"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "757a64f8-e317-4c7f-9e91-d07268d28903",
   "metadata": {},
   "source": [
    "## <a id=\"我想要一张大一点的图片\">我想要一张大一点的图片</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "64192beb-ed2b-4d94-9b7d-6dc577365a71",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "\n",
    "client = openai.OpenAI(api_key=\"sk-xxxx\")\n",
    "\n",
    "image_response = client.images.generate(\n",
    "    # 文本生成的提示词\n",
    "    prompt = \"菠菜水饺\",\n",
    "    model = \"dall-e-3\",\n",
    "    size = \"1792x1024\",\n",
    ")\n",
    "\n",
    "image_response"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c295c145-b29f-4fc0-be17-4da423d59b79",
   "metadata": {},
   "source": [
    "#  <a id=\"让GPT读出你的文本\">让GPT读出你的文本</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "47d72abe-bc2e-4638-84b7-e7c0b01d60c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "\n",
    "client = openai.OpenAI(api_key=\"sk-xxxx\")\n",
    "\n",
    "speech_response = client.audio.speech.create(\n",
    "    # TTS模型：tts-1（普清）、tts-1-hd（高清）\n",
    "    model=\"tts-1\",\n",
    "    # 需要转换成语音的文本，最长支持4096字节\n",
    "    input=\"大家好，我是菠菜！\",\n",
    "    voice=\"alloy\",\n",
    ")\n",
    "\n",
    "with open(\"speech_create_demo.mp3\", \"wb\") as file:\n",
    "    file.write(speech_response.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "30d82918-1da0-447e-bd24-c02548de68bf",
   "metadata": {},
   "source": [
    "#  <a id=\"换个声音说一说\">换个声音说一说</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94c2cfd8-a1c7-49ec-990d-86df255bb342",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "\n",
    "client = openai.OpenAI(api_key=\"sk-xxx\")\n",
    "\n",
    "speech_response = client.audio.speech.create(\n",
    "    # TTS模型：tts-1（普清）、tts-1-hd（高清）\n",
    "    model=\"tts-1\",\n",
    "    # 需要转换成语音的文本，最长支持4096字节\n",
    "    input=\"大家好，我是另一个菠菜！\",\n",
    "    # GPT提供6种音色：alloy、echo、fable、onyx、nova、shimmer，可以在：https://platform.openai.com/docs/guides/text-to-speech 各试听效果\n",
    "    voice=\"echo\",\n",
    ")\n",
    "\n",
    "with open(\"speech_create_echo.mp3\", \"wb\") as file:\n",
    "    file.write(speech_response.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "947a77fe-08e6-4080-8c3b-ad82e43feca4",
   "metadata": {},
   "source": [
    "#  <a id=\"说的快一点\">说的快一点</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "e388797b-45ba-4f5d-8457-d0ca682c021c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "\n",
    "client = openai.OpenAI(api_key=\"sk-xxxx\")\n",
    "\n",
    "speech_response = client.audio.speech.create(\n",
    "    # TTS模型：tts-1（普清）、tts-1-hd（高清）\n",
    "    model=\"tts-1\",\n",
    "    # 需要转换成语音的文本，最长支持4096字节\n",
    "    input=\"大家好，我是菠菜，说话贼快\",\n",
    "    voice=\"echo\",\n",
    "    # 语速，取值范围：0.25 - 4.0，默认为 1.0\n",
    "    speed=2.5 \n",
    ")\n",
    "\n",
    "with open(\"speech_create_quick.mp3\", \"wb\") as file:\n",
    "    file.write(speech_response.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e14a423b-fd98-4cf1-b0c1-fec8ca7796c9",
   "metadata": {},
   "source": [
    "#  <a id=\"关掉美颜、关掉滤镜\">关掉美颜、关掉滤镜</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "664efd09-bab2-4be5-8785-1de3abce628c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "\n",
    "client = openai.OpenAI(api_key=\"sk-xxxx\")\n",
    "\n",
    "image_response = client.images.generate(\n",
    "    # 文本生成的提示词\n",
    "    prompt = \"小兔子打架\",\n",
    "    model = \"dall-e-3\",\n",
    "    style=\"vivid\"\n",
    ")\n",
    "\n",
    "image_response"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "146b34be-dd6c-4b14-bc5c-2e7042ac8b93",
   "metadata": {},
   "source": [
    "#  <a id=\"还是喜欢朦胧美\">还是喜欢朦胧美</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8b305391-80dc-4672-b560-cfdc09425f08",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "\n",
    "client = openai.OpenAI(api_key=\"sk-xxxx\")\n",
    "\n",
    "image_response = client.images.generate(\n",
    "    # 文本生成的提示词\n",
    "    prompt = \"蜻蜓戏水\",\n",
    "    model = \"dall-e-3\",\n",
    "    style=\"natural\"\n",
    ")\n",
    "\n",
    "image_response"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "67f45bf8-1fe4-4e38-bf92-cdc0dcbb67a3",
   "metadata": {},
   "source": [
    "#  <a id=\"直接把图片内容给我\">直接把图片内容给我</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ff3264b9-f17e-4e55-88fe-5413e85e60aa",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "import base64\n",
    "\n",
    "client = openai.OpenAI(api_key=\"sk-xxxx\")\n",
    "\n",
    "image_response = client.images.generate(\n",
    "    # 文本生成的提示词\n",
    "    prompt = \"菠菜\",\n",
    "    model = \"dall-e-3\",\n",
    "    # 设置直接返回图片内容\n",
    "    response_format=\"b64_json\"\n",
    ")\n",
    "\n",
    "# 保存图片\n",
    "with open(\"菠菜.png\", 'wb') as file:\n",
    "    file.write(base64.b64decode(image_response.data[0].b64_json))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "90e91080-1bb0-4d3e-b725-7d27e8d42005",
   "metadata": {},
   "source": [
    "# <a id=\"学会插件开发，为GPT插上想象的翅膀\">学会插件开发，为GPT插上想象的翅膀</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2af3414b-76aa-4d7a-8d86-114f56ead1e1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "\n",
    "# 定义一个方法，用于获取菠菜老师的年龄\n",
    "def get_bocai_age():\n",
    "    return \"18岁\"\n",
    "\n",
    "# 定义messages\n",
    "messages=[{\n",
    "    \"role\": \"user\",\n",
    "    \"content\": \"hi，你好，请问菠菜老师多大了\",\n",
    "}]\n",
    "\n",
    "# 创建OpenAI的client，需要设置api_key\n",
    "client = openai.OpenAI(api_key='sk-xxxx')\n",
    "# 调用chat接口\n",
    "first_chat_completion = client.chat.completions.create(\n",
    "    messages=messages,\n",
    "    model='gpt-3.5-turbo-1106',\n",
    "    stream=False,\n",
    "    # 开启插件\n",
    "    tool_choice=\"auto\",\n",
    "    tools=[{\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            # tool的名字\n",
    "            \"name\": \"get_bocai_age\",\n",
    "            # tool的描述\n",
    "            \"description\": \"获取菠菜老师的年龄\",\n",
    "        }\n",
    "    }] \n",
    ")\n",
    "\n",
    "response_message = first_chat_completion.choices[0].message\n",
    "# 将GPT的答复记录下\n",
    "messages.append(response_message)\n",
    "\n",
    "# GPT返回的答复命中了插件\n",
    "if response_message.tool_calls is not None:\n",
    "    print(\"命中插件，进行调用\")\n",
    "    \n",
    "    # 将结果放入到messages中\n",
    "    messages.append({\n",
    "        \"role\": \"tool\",\n",
    "        # 调用Func获取菠菜老师的年龄\n",
    "        \"content\": get_bocai_age(),\n",
    "        # 赋值GPT的返回中的tool call id，用于唯一标识一次tool call\n",
    "        \"tool_call_id\": response_message.tool_calls[0].id\n",
    "    })\n",
    "\n",
    "    # 发起二次请求\n",
    "    second_chat_completion = client.chat.completions.create(\n",
    "        messages=messages,\n",
    "        model='gpt-3.5-turbo-1106',\n",
    "        stream=False,\n",
    "        # 开启插件\n",
    "        tool_choice=\"auto\",\n",
    "        tools=[{\n",
    "            \"type\": \"function\",\n",
    "            \"function\": {\n",
    "                # tool的名字\n",
    "                \"name\": \"get_bocai_age\",\n",
    "                # tool的描述\n",
    "                \"description\": \"获取菠菜老师的年龄\",\n",
    "            }\n",
    "        }] \n",
    "    )\n",
    "\n",
    "    print(second_chat_completion.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b41a9154-d99c-4f73-bf6e-b3d36ad49b11",
   "metadata": {},
   "source": [
    "# <a id=\"数学插件，让GPT成为数学天才\">数学插件，让GPT成为数学天才</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ea5881f4-4dcf-4daf-aa93-22ead0f5e89c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "import json\n",
    "import requests\n",
    "\n",
    "# 定义一个方法，用于数学计算\n",
    "def math_cal(param):\n",
    "    math_exp = json.loads(param)[\"math_exp\"]\n",
    "    print(\"GPT期望计算的公式为：\", math_exp)\n",
    "    return {\n",
    "        \"content\": eval(math_exp)\n",
    "    }\n",
    "\n",
    "# 定义messages\n",
    "messages=[{\n",
    "    \"role\": \"user\",\n",
    "    \"content\": \"帮我计算下3乘4是多少\",\n",
    "}]\n",
    "\n",
    "# 创建OpenAI的client，需要设置api_key\n",
    "client = openai.OpenAI(api_key='sk-xxxx')\n",
    "\n",
    "\n",
    "def ask_gpt():\n",
    "    return client.chat.completions.create(\n",
    "        messages=messages,\n",
    "        model='gpt-3.5-turbo-1106',\n",
    "        stream=False,\n",
    "        # 开启插件\n",
    "        tool_choice=\"auto\",\n",
    "        tools=[{\n",
    "            \"type\": \"function\",\n",
    "            \"function\": {\n",
    "                # tool的名字\n",
    "                \"name\": \"math_cal\",\n",
    "                # tool的描述\n",
    "                \"description\": \"数学公式计算器\",\n",
    "                # 定义\n",
    "                \"parameters\": {\n",
    "                    \"type\": \"object\",\n",
    "                    \"properties\": {\n",
    "                        # 参数定义\n",
    "                        \"math_exp\": {\n",
    "                            \"type\": \"string\",\n",
    "                            \"description\": \"数学计算公式\",\n",
    "                        },\n",
    "                    },\n",
    "                    # 规定哪些参数是必须的\n",
    "                    \"required\": [\"math_exp\"],\n",
    "                },\n",
    "            }\n",
    "        }]\n",
    "    )\n",
    "\n",
    "    \n",
    "\n",
    "# 调用chat接口\n",
    "response_message = ask_gpt().choices[0].message\n",
    "# 将GPT的答复记录下\n",
    "messages.append(response_message)\n",
    "\n",
    "# GPT返回的答复命中了插件\n",
    "if response_message.tool_calls is not None:\n",
    "    print(\"命中插件，进行调用\")\n",
    "    tool_call = response_message.tool_calls[0]\n",
    "    \n",
    "    # 将结果放入到messages中\n",
    "    messages.append({\n",
    "        \"role\": \"tool\",\n",
    "        # 调用Func计算数学公式，tool_call.function.arguments为GPT返回调用Func的所需参数\n",
    "        \"content\": json.dumps(math_cal(tool_call.function.arguments)),\n",
    "        # 赋值GPT的返回中的tool call id，用于唯一标识一次tool call\n",
    "        \"tool_call_id\": tool_call.id\n",
    "    })\n",
    "\n",
    "    # 发起二次请求\n",
    "    second_chat_completion = ask_gpt()\n",
    "\n",
    "    print(second_chat_completion.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b513185-9364-4bb0-9ffa-ac3457654ff1",
   "metadata": {},
   "source": [
    "# <a id=\"代码插件，让GPT具有创造力\">代码插件，让GPT具有创造力</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9b6c8385-892c-449b-ab83-9f70b82099ea",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "import json\n",
    "\n",
    "# 定义一个方法，用于执行代码\n",
    "def code_exec(param):\n",
    "    code = json.loads(param)[\"code\"]\n",
    "    print(\"GPT期望执行的代码\", code)\n",
    "\n",
    "    rs = exec(code)\n",
    "    if rs is None or rs == \"\":\n",
    "        rs = eval(code)\n",
    "    \n",
    "    return {\n",
    "        \"content\": str(rs)\n",
    "    }\n",
    "\n",
    "# 定义messages\n",
    "messages=[{\n",
    "    \"role\": \"system\",\n",
    "    \"content\": \"你是一个代码生成器，会为你定制tools来辅助你执行你生成的代码，但是请记住代码最后要对结果进行打印\",\n",
    "},{\n",
    "    \"role\": \"user\",\n",
    "    \"content\": \"帮我计算下1+2+3+..+100，最后是多少\",\n",
    "}]\n",
    "\n",
    "# 创建OpenAI的client，需要设置api_key\n",
    "client = openai.OpenAI(api_key='sk-xxxx')\n",
    "\n",
    "\n",
    "def ask_gpt():\n",
    "    return client.chat.completions.create(\n",
    "        messages=messages,\n",
    "        model='gpt-3.5-turbo-1106',\n",
    "        stream=False,\n",
    "        # 开启插件\n",
    "        tool_choice=\"auto\",\n",
    "        tools=[{\n",
    "            \"type\": \"function\",\n",
    "            \"function\": {\n",
    "                # tool的名字\n",
    "                \"name\": \"code_exec\",\n",
    "                # tool的描述\n",
    "                \"description\": \"python代码执行器\",\n",
    "                # 定义\n",
    "                \"parameters\": {\n",
    "                    \"type\": \"object\",\n",
    "                    \"properties\": {\n",
    "                        # 参数定义\n",
    "                        \"code\": {\n",
    "                            \"type\": \"string\",\n",
    "                            \"description\": \"需要执行的代码\",\n",
    "                        },\n",
    "                    },\n",
    "                    # 规定哪些参数是必须的\n",
    "                    \"required\": [\"code\"],\n",
    "                },\n",
    "            }\n",
    "        }]\n",
    "    )\n",
    "\n",
    "    \n",
    "\n",
    "# 调用chat接口\n",
    "response_message = ask_gpt().choices[0].message\n",
    "# 将GPT的答复记录下\n",
    "messages.append(response_message)\n",
    "\n",
    "# GPT返回的答复命中了插件\n",
    "if response_message.tool_calls is not None:\n",
    "    print(\"命中插件，进行调用\")\n",
    "    tool_call = response_message.tool_calls[0]\n",
    "    \n",
    "    # 将结果放入到messages中\n",
    "    messages.append({\n",
    "        \"role\": \"tool\",\n",
    "        # 调用Func来执行代码，tool_call.function.arguments为GPT返回调用Func的所需参数\n",
    "        \"content\": json.dumps(code_exec(tool_call.function.arguments)),\n",
    "        # 赋值GPT的返回中的tool call id，用于唯一标识一次tool call\n",
    "        \"tool_call_id\": tool_call.id\n",
    "    })\n",
    "\n",
    "    # 发起二次请求\n",
    "    second_chat_completion = ask_gpt()\n",
    "\n",
    "    print(second_chat_completion.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b5bb3422-0abd-4d33-a9cf-e32fcc08ff63",
   "metadata": {},
   "source": [
    "# <a id=\"文件插件，保存GPT对你诉说的秘密\">文件插件，保存GPT对你诉说的秘密</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "bc80d66a-1e1d-4e99-aec5-fe90677849b0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "命中插件，进行调用\n",
      "GPT的秘密： 你是我遇到过最有趣的人之一\n",
      "秘密已记录。有什么可以帮你的吗？\n"
     ]
    }
   ],
   "source": [
    "import openai\n",
    "import json\n",
    "\n",
    "# 定义一个方法，用于保存秘密\n",
    "def secret_saver(param):\n",
    "    secret = json.loads(param)[\"secret\"]\n",
    "    print(\"GPT的秘密：\", secret)\n",
    "    with open(\"secret.txt\", \"w\") as file:\n",
    "        file.write(secret)\n",
    "    return \"ok\"\n",
    "\n",
    "# 定义messages\n",
    "messages=[{\n",
    "    \"role\": \"system\",\n",
    "    \"content\": \"你是一个秘密制造者\",\n",
    "},{\n",
    "    \"role\": \"user\",\n",
    "    \"content\": \"随便告诉我一个秘密\",\n",
    "}]\n",
    "\n",
    "# 创建OpenAI的client，需要设置api_key\n",
    "client = openai.OpenAI(api_key='sk-xxxx')\n",
    "\n",
    "\n",
    "def ask_gpt():\n",
    "    return client.chat.completions.create(\n",
    "        messages=messages,\n",
    "        model='gpt-3.5-turbo-1106',\n",
    "        stream=False,\n",
    "        # 开启插件\n",
    "        tool_choice=\"auto\",\n",
    "        tools=[{\n",
    "            \"type\": \"function\",\n",
    "            \"function\": {\n",
    "                # tool的名字\n",
    "                \"name\": \"secret_saver\",\n",
    "                # tool的描述\n",
    "                \"description\": \"秘密的记录者，用于记录你说的秘密\",\n",
    "                # 定义\n",
    "                \"parameters\": {\n",
    "                    \"type\": \"object\",\n",
    "                    \"properties\": {\n",
    "                        # 参数定义\n",
    "                        \"secret\": {\n",
    "                            \"type\": \"string\",\n",
    "                            \"description\": \"秘密\",\n",
    "                        },\n",
    "                    },\n",
    "                    # 规定哪些参数是必须的\n",
    "                    \"required\": [\"secret\"],\n",
    "                },\n",
    "            }\n",
    "        }]\n",
    "    )\n",
    "\n",
    "    \n",
    "\n",
    "# 调用chat接口\n",
    "response_message = ask_gpt().choices[0].message\n",
    "# 将GPT的答复记录下\n",
    "messages.append(response_message)\n",
    "\n",
    "# GPT返回的答复命中了插件\n",
    "if response_message.tool_calls is not None:\n",
    "    print(\"命中插件，进行调用\")\n",
    "    tool_call = response_message.tool_calls[0]\n",
    "    \n",
    "    # 将结果放入到messages中\n",
    "    messages.append({\n",
    "        \"role\": \"tool\",\n",
    "        # 调用Func来执行代码，tool_call.function.arguments为GPT返回调用Func的所需参数\n",
    "        \"content\": json.dumps(secret_saver(tool_call.function.arguments)),\n",
    "        # 赋值GPT的返回中的tool call id，用于唯一标识一次tool call\n",
    "        \"tool_call_id\": tool_call.id\n",
    "    })\n",
    "\n",
    "    # 发起二次请求\n",
    "    second_chat_completion = ask_gpt()\n",
    "\n",
    "    print(second_chat_completion.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "37281f29-0f1d-4f95-829f-d7956ad590c9",
   "metadata": {},
   "source": [
    "# <a id=\"多插件示例\">多插件示例</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "5b76d00a-7ace-4585-bfd1-660caa3f24e3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "命中插件，进行调用\n",
      "GPT的秘密： 我是一个AI助手\n",
      "秘密已记录。现在，告诉我你想了解的内容，或者有什么问题需要帮助吗？\n"
     ]
    }
   ],
   "source": [
    "import openai\n",
    "import json\n",
    "\n",
    "# 定义一个方法，用于保存秘密\n",
    "def secret_saver(param):\n",
    "    secret = json.loads(param)[\"secret\"]\n",
    "    print(\"GPT的秘密：\", secret)\n",
    "    with open(\"secret.txt\", \"w\") as file:\n",
    "        file.write(secret)\n",
    "    return \"ok\"\n",
    "\n",
    "def code_exec(param):\n",
    "    code = json.loads(param)[\"code\"]\n",
    "    print(\"GPT期望执行的代码\", code)\n",
    "\n",
    "    rs = exec(code)\n",
    "    if rs is None or rs == \"\":\n",
    "        rs = eval(code)\n",
    "    \n",
    "    return {\n",
    "        \"content\": str(rs)\n",
    "    }\n",
    "\n",
    "\n",
    "# 定义messages\n",
    "messages=[{\n",
    "    \"role\": \"system\",\n",
    "    \"content\": \"你是一个秘密制造者\",\n",
    "},{\n",
    "    \"role\": \"user\",\n",
    "    \"content\": \"随便告诉我一个秘密\",\n",
    "}]\n",
    "\n",
    "# 创建OpenAI的client，需要设置api_key\n",
    "client = openai.OpenAI(api_key='sk-xxxx')\n",
    "\n",
    "\n",
    "def ask_gpt():\n",
    "    return client.chat.completions.create(\n",
    "        messages=messages,\n",
    "        model='gpt-3.5-turbo-1106',\n",
    "        stream=False,\n",
    "        # 开启插件\n",
    "        tool_choice=\"auto\",\n",
    "        tools=[{\n",
    "            \"type\": \"function\",\n",
    "            \"function\": {\n",
    "                # tool的名字\n",
    "                \"name\": \"secret_saver\",\n",
    "                # tool的描述\n",
    "                \"description\": \"秘密的记录者，用于记录你说的秘密\",\n",
    "                # 定义\n",
    "                \"parameters\": {\n",
    "                    \"type\": \"object\",\n",
    "                    \"properties\": {\n",
    "                        # 参数定义\n",
    "                        \"secret\": {\n",
    "                            \"type\": \"string\",\n",
    "                            \"description\": \"秘密\",\n",
    "                        },\n",
    "                    },\n",
    "                    # 规定哪些参数是必须的\n",
    "                    \"required\": [\"secret\"],\n",
    "                },\n",
    "            }\n",
    "        },{\n",
    "            \"type\": \"function\",\n",
    "            \"function\": {\n",
    "                # tool的名字\n",
    "                \"name\": \"code_exec\",\n",
    "                # tool的描述\n",
    "                \"description\": \"python代码执行器\",\n",
    "                # 定义\n",
    "                \"parameters\": {\n",
    "                    \"type\": \"object\",\n",
    "                    \"properties\": {\n",
    "                        # 参数定义\n",
    "                        \"code\": {\n",
    "                            \"type\": \"string\",\n",
    "                            \"description\": \"需要执行的代码\",\n",
    "                        },\n",
    "                    },\n",
    "                    # 规定哪些参数是必须的\n",
    "                    \"required\": [\"code\"],\n",
    "                },\n",
    "            }\n",
    "        }]\n",
    "    )\n",
    "\n",
    "\n",
    "# 调用chat接口\n",
    "response_message = ask_gpt().choices[0].message\n",
    "# 将GPT的答复记录下\n",
    "messages.append(response_message)\n",
    "\n",
    "# GPT返回的答复命中了插件\n",
    "if response_message.tool_calls is not None:\n",
    "    print(\"命中插件，进行调用\")\n",
    "\n",
    "    # 遍历tool_calls\n",
    "    for tool_call in response_message.tool_calls:\n",
    "        tool_name = tool_call.function.name\n",
    "        tool_args = tool_call.function.arguments\n",
    "        \n",
    "        # 判断是否命中了secret_saver\n",
    "        if tool_name == \"secret_saver\":\n",
    "            messages.append({\n",
    "               \"role\": \"tool\",\n",
    "               # 调用Func来执行代码，tool_call.function.arguments为GPT返回调用Func的所需参数\n",
    "               \"content\": json.dumps(secret_saver(tool_args)),\n",
    "               # 赋值GPT的返回中的tool call id，用于唯一标识一次tool call\n",
    "               \"tool_call_id\": tool_call.id\n",
    "            })\n",
    "\n",
    "        # 判断是否命中了code_exec\n",
    "        elif tool_name == \"code_exec\":\n",
    "            messages.append({\n",
    "                \"role\": \"tool\",\n",
    "                # 调用Func来执行代码，tool_call.function.arguments为GPT返回调用Func的所需参数\n",
    "                \"content\": json.dumps(code_exec(tool_args)),\n",
    "                # 赋值GPT的返回中的tool call id，用于唯一标识一次tool call\n",
    "                \"tool_call_id\": tool_call.id\n",
    "            })\n",
    "\n",
    "    # 发起二次请求\n",
    "    second_chat_completion = ask_gpt()\n",
    "\n",
    "    print(second_chat_completion.choices[0].message.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9042b135-0b46-4d30-b851-72aca15f7ef1",
   "metadata": {},
   "source": [
    "# <a id=\"客服-创建带知识和Tools的客服\">客服 - 创建带知识和Tools的客服</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "59b22637-a032-488a-9304-723fa8aeb110",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Done\n"
     ]
    }
   ],
   "source": [
    "import openai\n",
    "\n",
    "client = openai.OpenAI(api_key=\"sk-xxxx\")\n",
    "\n",
    "# 上传客服知识文件\n",
    "file_knowledge_call_center = client.files.create(\n",
    "    file=open(\"assistant_knowledge_call_center.txt\", \"rb\"),\n",
    "    # 文件用途，目前取值为：fine-tune、assistants\n",
    "    purpose=\"assistants\"\n",
    ")\n",
    "\n",
    "assistant_call_center = client.beta.assistants.create(\n",
    "    name=\"智能客服\",\n",
    "    # 功能描述，最长 512 字符\n",
    "    description=\"24小时为您服务\",\n",
    "    # 功能prompt，最长 32768 字符\n",
    "    instructions=\"作为智能客服，严格按照你的知识回答用户的问题，若不在知识范围内的，则委婉拒绝\",\n",
    "    # 这里gpt-3.5跟gpt-4类的模型均可使用\n",
    "    model=\"gpt-3.5-turbo-1106\",\n",
    "    # assistants开启的工具，共有三种类型：code_interpreter、retrieval、function（与Chat接口的Tool一致）\n",
    "    tools=[\n",
    "        {\n",
    "            # gpt提供的代码生成与执行工具\n",
    "            \"type\": \"code_interpreter\",\n",
    "        },\n",
    "        {\n",
    "            # gpt提供的检索功能，若上传了知识文件，则可以查询，类似于智能客服/知识库\n",
    "            \"type\": \"retrieval\",\n",
    "        }\n",
    "    ],\n",
    "    # 知识文件，通过File接口上传的\n",
    "    file_ids=[file_knowledge_call_center.id]\n",
    ")\n",
    "\n",
    "print(\"Done\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "573427d4-59e5-4ca5-8e24-6d404c0fa3ec",
   "metadata": {},
   "source": [
    "# <a id=\"客服-创建一个用户的会话和消息\">客服 - 创建一个用户的会话和消息</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "18593db3-5ee4-4dcf-8d15-90b5028b8fd1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Done\n"
     ]
    }
   ],
   "source": [
    "import openai\n",
    "\n",
    "client = openai.OpenAI(api_key=\"sk-xxxx\")\n",
    "\n",
    "thread_zhangsan = client.beta.threads.create(\n",
    "    # 张三的信息\n",
    "    metadata={\n",
    "        \"姓名\": \"张三\",\n",
    "        \"年龄\": 36,\n",
    "        \"性别\": \"男\"\n",
    "    }\n",
    ")\n",
    "\n",
    "# 创建一个消息，用于问答\n",
    "message = client.beta.threads.messages.create(\n",
    "    # message 所归属的thread\n",
    "    thread_id=thread_zhangsan.id,  \n",
    "    # 类似ChatCompletion的message的role\n",
    "    role=\"user\",          \n",
    "    content=\"你们的商城叫什么名字\",\n",
    ")\n",
    "\n",
    "print(\"Done\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "09ec3eb1-ea2f-4873-8339-46c74ed2999a",
   "metadata": {},
   "source": [
    "# <a id=\"客服-排队并等待客服答复\">客服 - 排队并等待客服答复</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1ac22b38-3352-422d-bd34-09213e3497e7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "import json\n",
    "import openai\n",
    "\n",
    "client = openai.OpenAI(api_key=\"sk-xxxx\")\n",
    "\n",
    "# 创建咨询队列\n",
    "run = client.beta.threads.runs.create(\n",
    "    thread_id=thread_zhangsan.id,\n",
    "    assistant_id=assistant_call_center.id,\n",
    ")\n",
    "\n",
    "# 等待询问结果\n",
    "while run.status == \"queued\" or run.status == \"in_progress\":\n",
    "    run = client.beta.threads.runs.retrieve(\n",
    "        thread_id=thread_zhangsan.id,\n",
    "        run_id=run.id,\n",
    "    )\n",
    "    time.sleep(0.5)\n",
    "\n",
    "# 获取询问结果\n",
    "messages = client.beta.threads.messages.list(\n",
    "    thread_id=thread_zhangsan.id, order=\"asc\", after=message.id\n",
    ")\n",
    "\n",
    "display(json.loads(messages.model_dump_json()))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fd13e1df-6f8c-46ae-afc9-7e46b75bb2e3",
   "metadata": {},
   "source": [
    "# <a id=\"客服-完整流程\">客服 - 完整流程</a>\n",
    "[返回索引](#索引)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "25d37e72-6751-4fa9-9185-fddc92446114",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "import time\n",
    "import json\n",
    "\n",
    "client = openai.OpenAI(api_key=\"sk-xxxx\")\n",
    "\n",
    "# 上传客服知识文件\n",
    "file_knowledge_call_center = client.files.create(\n",
    "    file=open(\"assistant_knowledge_call_center.txt\", \"rb\"),\n",
    "    # 文件用途，目前取值为：fine-tune、assistants\n",
    "    purpose=\"assistants\"\n",
    ")\n",
    "\n",
    "assistant_call_center = client.beta.assistants.create(\n",
    "    name=\"智能客服\",\n",
    "    # 功能描述，最长 512 字符\n",
    "    description=\"24小时为您服务\",\n",
    "    # 功能prompt，最长 32768 字符\n",
    "    instructions=\"作为智能客服，严格按照你的知识回答用户的问题，若不在知识范围内的，则委婉拒绝\",\n",
    "    # 这里gpt-3.5跟gpt-4类的模型均可使用\n",
    "    model=\"gpt-3.5-turbo-1106\",\n",
    "    # assistants开启的工具，共有三种类型：code_interpreter、retrieval、function（与Chat接口的Tool一致）\n",
    "    tools=[\n",
    "        {\n",
    "            # gpt提供的代码生成与执行工具\n",
    "            \"type\": \"code_interpreter\",\n",
    "        },\n",
    "        {\n",
    "            # gpt提供的检索功能，若上传了知识文件，则可以查询，类似于智能客服/知识库\n",
    "            \"type\": \"retrieval\",\n",
    "        }\n",
    "    ],\n",
    "    # 知识文件，通过File接口上传的\n",
    "    file_ids=[file_knowledge_call_center.id]\n",
    ")\n",
    "\n",
    "thread_zhangsan = client.beta.threads.create(\n",
    "    # 张三的信息\n",
    "    metadata={\n",
    "        \"姓名\": \"张三\",\n",
    "        \"年龄\": 36,\n",
    "        \"性别\": \"男\"\n",
    "    }\n",
    ")\n",
    "\n",
    "# 创建一个消息，用于问答\n",
    "message = client.beta.threads.messages.create(\n",
    "    # message 所归属的thread\n",
    "    thread_id=thread_zhangsan.id,  \n",
    "    # 类似ChatCompletion的message的role\n",
    "    role=\"user\",          \n",
    "    content=\"你们的商城叫什么名字\",\n",
    ")\n",
    "\n",
    "# 创建咨询队列\n",
    "run = client.beta.threads.runs.create(\n",
    "    thread_id=thread_zhangsan.id,\n",
    "    assistant_id=assistant_call_center.id,\n",
    ")\n",
    "\n",
    "# 等待询问结果\n",
    "while run.status == \"queued\" or run.status == \"in_progress\":\n",
    "    run = client.beta.threads.runs.retrieve(\n",
    "        thread_id=thread_zhangsan.id,\n",
    "        run_id=run.id,\n",
    "    )\n",
    "    time.sleep(0.5)\n",
    "\n",
    "# 获取询问结果\n",
    "messages = client.beta.threads.messages.list(\n",
    "    thread_id=thread_zhangsan.id, order=\"asc\", after=message.id\n",
    ")\n",
    "\n",
    "display(json.loads(messages.model_dump_json()))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
